/*
 * Copyright (c) 2016 moondev.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.moondev.moonlog.example.moonlog.monitor.service.impl;

import java.util.List;

import cn.moondev.moonlog.example.moonlog.monitor.dao.SqlMonitorDao;
import cn.moondev.moonlog.example.moonlog.monitor.entity.SqlMonitor;
import cn.moondev.moonlog.example.moonlog.monitor.service.SqlMonitorService;
import cn.moondev.moonlog.example.moonlog.monitor.utils.Page;
import cn.moondev.moonlog.example.moonlog.monitor.utils.TableBuilder;
import com.google.common.base.Preconditions;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


@Service("sqlMonitorService")
public class SqlMonitorServiceImpl implements SqlMonitorService {

	@Autowired
	SqlMonitorDao sqlMonitorDao;

	@Override
	public Page<SqlMonitor> list(String sys, int index, int size, String start, String end, String date) {
		// 验证数据
		Preconditions.checkNotNull(sys,"sys参数不能为空");
		if (size <= 0) {
			size = 10;
		}
		if (index <= 0) {
			index = 1;
		}
		Page<SqlMonitor> page = new Page<SqlMonitor>(index,size);
		String tableName = TableBuilder.buildSqlMonitorTableName(new DateTime());
		// 2015-12-12 12:12:12格式日期 ---> 毫秒
		long start_ms = 0,end_ms = 0;
		if(StringUtils.isEmpty(date)) { 
			start_ms = new DateTime(start.replace(" ", "T")).getMillis();
			end_ms = new DateTime(end.replace(" ", "T")).getMillis();
		}
		List<SqlMonitor> list = sqlMonitorDao.list(sys, page.getFirst(), size, start_ms, end_ms, date, tableName);
		long total = sqlMonitorDao.count(sys, start_ms, end_ms, date, tableName);
		page.setResult(list);
		page.setTotalCount(total);
		return page;
	}

}
